<template>
  <div>
    <div v-show="addDialogVisible !== true && modifyDialogVisible !== true && detailDialogVisible !== true">
      <!-- 炎哥写的 -->
      <el-card>

        <el-input v-model="title" placeholder="请输入标题" style="width: 200px;margin: 0 20px;"></el-input>
        <el-date-picker v-model="dateRange" type="daterange" align="right"
                        value-format="yyyy-MM-dd HH:mm:ss" unlink-panels range-separator="--"
                        start-placeholder="选择日期范围"
                        end-placeholder="选择日期范围" :picker-options="pickerOptions" style="margin: 0 20px; ">
        </el-date-picker>
        <el-select v-model="subjectName" placeholder="筛选学科" clearable style="width: 200px;margin: 0 20px;">
          <el-option v-for="item in subject" :key="item.name" :label="item.name" :value="item.name">
          </el-option>
        </el-select>
        <!--选择标签作为筛选条件-->
        <el-select v-model="labelName" placeholder="筛选标签" clearable style="width: 200px;margin: 0 20px;">
          <el-option v-for="item in dynamicTags" :key="item.name" :label="item.name" :value="item.name">
          </el-option>
        </el-select>

        <div style="float: right;margin: 20px 0 20px 16px">
          <el-button type="primary" style="margin: 0 10px;" @click="searchMistakes">查找</el-button>
          <el-button type="info" style="margin: 0 10px;" @click="clear">清空</el-button>
          <el-button type="primary" style="margin: 0 10px;" @click="addMistake">新增</el-button>
        </div>

        <el-table :data="mistakeData">
          <el-table-column type="index" label="序号" min-width="2" align="center">
            <template slot-scope="scope">
              <span>{{ (current - 1) * pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="questionTitle" label="标题" min-width="1" align="center"></el-table-column>
          <el-table-column prop="questionContent" label="错题内容" min-width="2"
                           align="center"></el-table-column>
          <el-table-column prop="questionImage" label="错题图片" min-width="2" align="center">
            <template slot-scope="scope">
              <el-image v-if="scope.row.questionImage" :src="scope.row.questionImage"
                        :preview-src-list="[scope.row.questionImage]"></el-image>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="subject" label="学科" min-width="1" align="center"></el-table-column>
          <el-table-column prop="subject" label="标签" min-width="2" align="center">
            <template slot-scope="scope">
              <el-tag v-for="(item, index) in scope.row.labelList" :key="index">{{ item }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="2">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="modify(scope.row)">修改</el-button>
              <el-button type="primary" size="small" @click="details(scope.row)">详情</el-button>
              <el-popconfirm title="确定删除该错题吗？" @confirm="deleteMistake(scope.row.id)">
                <el-button slot="reference" type="danger" size="small" style="margin-left: 10px;">删除
                </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

      </el-card>
      <el-pagination style="padding: 20px 0" :current-page="current" @current-change="handleCurrentChange"
                     @size-change="handleSizeChange" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <div v-show="addDialogVisible == true">
      <el-form ref="form" :model="addMistakeData" label-width="85px">
        <el-form-item label="标题">
          <el-input v-model="addMistakeData.questionTitle"></el-input>
        </el-form-item>
        <el-form-item label="错题图片">
          <div style="float: left;">
            <el-upload ref="addUpload" class="avatar-uploader"
                       action="http://106.55.170.119:9090/mistakebook/question/upload" :limit=1 name="questionImage"
                       :on-success="addSuccess" :on-change="addChange" :auto-upload="false">
              <div class="image-container">
                <el-image v-if="addMistakeData.questionImage"
                          :src="addMistakeData.questionImage"></el-image>
                <i v-else class="el-icon-plus avatar-icon"></i>
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <div style="display: flex;">
          <el-form-item label="学科">
            <el-select v-model="addMistakeData.subject" placeholder="请选择" style="float: left;">
              <el-option v-for="item in subject" :key="item.name" :label="item.name" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签">
            <el-select v-model="addMistakeData.labelList" placeholder="请选择" multiple filterable allow-create
                       style="float: left;">
              <el-option v-for="item in dynamicTags" :key="item.name" :label="item.name"
                         :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="优先级">
            <el-select v-model="addMistakeData.priority" placeholder="请选择" clearable style="float: left">
              <el-option v-for="item in priorityList" :key="item.value" :value="item.value"
                         :label="item.label">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="错题内容">
          <el-input v-model="addMistakeData.questionContent" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="答案">
          <el-input v-model="addMistakeData.questionAnswer" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="分析">
          <el-input v-model="addMistakeData.questionAnalysis" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="总结">
          <el-input v-model="addMistakeData.questionSummary" type="textarea" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="addCancel">取 消</el-button>
                <el-button type="primary" @click="addConfirm()">确 定</el-button>
            </span>
    </div>
    <div v-show="modifyDialogVisible == true">
      <el-form ref="form" :model="selectedMistake" label-width="85px">
        <el-form-item label="标题">
          <el-input v-model="selectedMistake.questionTitle"></el-input>
        </el-form-item>
        <el-form-item label="错题内容">
          <el-input v-model="selectedMistake.questionContent" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="错题图片">
          <div style="float: left;">
            <el-upload ref="upload" class="avatar-uploader"
                       action="http://106.55.170.119:9090/mistakebook/question/upload" :limit=1
                       :on-success="handleAvatarSuccess" name="questionImage" :on-change="handleAvatarChange"
                       :auto-upload="false">
              <div class="image-container" @click="deleteFiles()">
                <el-image :src="imageUrl"></el-image>
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </el-upload>
          </div>


        </el-form-item>
        <el-form-item label="学科">
          <el-select v-model="selectedMistake.subject" placeholder="请选择" style="float: left;">
            <el-option v-for="item in subject" :key="item.name" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="selectedMistake.labelList" placeholder="请选择" multiple filterable allow-create
                     style="float: left;">
            <el-option v-for="item in dynamicTags" :key="item.name" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="selectedMistake.priority" placeholder="请选择" clearable style="float: left">
            <el-option v-for="item in priorityList" :key="item.value" :value="item.value"
                       :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="答案">
          <el-input v-model="selectedMistake.questionAnswer" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="分析">
          <el-input v-model="selectedMistake.questionAnalysis" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="总结">
          <el-input v-model="selectedMistake.questionSummary" type="textarea" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="modifyDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirm()">确 定</el-button>
            </span>

    </div>
    <div v-show="detailDialogVisible == true" class="mistake-display">
      <el-form ref="form" :model="selectedMistake" label-width="85px" class="mistake-form">
        <el-form-item label="标题">
          <el-input v-model="selectedMistake.questionTitle" placeholder="请输入标题" readonly></el-input>
        </el-form-item>

        <el-form-item label="错题图片">
          <el-image :src="selectedMistake.questionImage"
                    :preview-src-list="[selectedMistake.questionImage]"></el-image>
        </el-form-item>
        <el-form-item label="学科与标签">
          <div style="display: flex;">
            <el-tag class="tag-item">{{ selectedMistake.subject }}</el-tag>
            <el-tag class="tag-item">{{ selectedMistake.priority }}</el-tag>
            <el-tag class="tag-item" v-for="(item, index) in selectedMistake.labelList" :key="index">{{
                item
              }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="错题内容">
          <el-input v-model="selectedMistake.questionContent" placeholder="请输入错题内容" type="textarea" readonly
                    :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="答案">
          <el-input v-model="selectedMistake.questionAnswer" placeholder="请输入答案" type="textarea" readonly
                    :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="分析">
          <el-input v-model="selectedMistake.questionAnalysis" placeholder="请输入分析" type="textarea" readonly
                    :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="总结">
          <el-input v-model="selectedMistake.questionSummary" placeholder="请输入总结" type="textarea" readonly
                    :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="detailDialogVisible = false">返 回</el-button>
            </span>
    </div>

  </div>

</template>

<script>
import {reqGetMistakes, reqDeleteMistake, reqModifyMistake, reqGetAllTag, reqSearchMistakes} from '@/api/mistake';

export default {
  name: 'mistakePage',
  components: {},
  data() {
    return {
      /* 变量名很多难以解释 除了有注释的那几个根据需要修改
      其他的尽量不要去动它 如果需要其他变量 重新定义新变量名即可 */

      //title到difficulty是筛选条件
      title: '',
      dateRange: [],
      current: 1,
      pageSize: 5,
      total: 0,
      subjectName: '',
      labelName: '',
      difficulty: '',

      //日期选择的便捷选项
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

      subject: [
        {name: "语文"},
        {name: "数学"},
        {name: "英语"},
        {name: "物理"},
        {name: "化学"},
        {name: "生物"},
        {name: "政治"},
        {name: "历史"},
        {name: "地理"},
      ],
      dialogVisible: false,
      dynamicTags: [
        {
          id: '',
          name: ""
        }
      ],
      //优先级数组
      priorityList: [
        {
          value: '重点',
          label: '重点'
        },
        {
          value: '高',
          label: '高'
        },
        {
          value: '中',
          label: '中'
        },
        {
          value: '低',
          label: '低'
        },
        {
          value: '冷门',
          label: '冷门'
        },
      ],
      inputVisible: false,
      inputValue: '',
      //在页面显示的错题数据数组
      mistakeData: [],
      //新增错题页面的错题数据
      addMistakeData: {
        userId: 1,
        labelList: [],
        questionContent: '',
        questionSummary: '',
        questionTitle: '',
        questionAnswer: '',
        subject: '',
        priority: '',
        questionImage: '',
        questionAnalysis: ''
      },
      //点击修改按钮、详情按钮、删除按钮获取到的错题数据
      selectedMistake: {},
      //控制修改页面关闭和显示的变量
      addDialogVisible: false,
      //控制修改页面关闭和显示的变量
      modifyDialogVisible: false,
      //控制详情页面关闭和显示的变量
      detailDialogVisible: false,
      imageUrl: '',
      upload: '',
      photo: false,
      count: 0,
      fileCount: 0,
      addFlag: false,

    };
  },
  methods: {
    //清空筛选条件
    clear() {
      this.title = ''
      this.dateRange = []
      this.current = 1
      this.pageSize = 5
      this.total = 0
      this.subjectName = ''
      this.labelName = ''
      this.difficulty = ''
      this.searchMistakes()
    },
    //页码变化
    handleCurrentChange(val) {
      this.current = val
      this.searchMistakes()
    },
    //页容量变化
    handleSizeChange(val) {
      this.pageSize = val
      this.searchMistakes()
    },
    //查询错题
    // searchMistakes() {
    //     console.log(this.dateRange)
    // },
    async searchMistakes() {
      let result = await reqSearchMistakes(this.title, this.current, this.pageSize, this.subjectName,
          this.labelName, this.dateRange?.at(0), this.dateRange?.at(1))
      this.total = result.data.total
      this.mistakeData = result.data.records
    },
    //获取所有标签
    async getAllTag() {
      let result = await reqGetAllTag()
      this.dynamicTags = result.data
    },
    //显示所有错题
    async getMistakes() {
      let result = await reqGetMistakes()
      this.total = result.data.total
      this.mistakeData = result.data.records
    },
    //新增按钮
    addMistake() {
      this.clearAddMistake()
      this.$refs.addUpload.clearFiles()
      this.addDialogVisible = true
    },
    //新增错题页面的关闭按钮
    /* addClose() {
        if (this.addFlag) {
            this.addFlag = !this.addFlag
            this.$refs.upload.clearFiles()
        }
    },
    beforeClose() {
        this.clearAddMistake()
        this.addDialogVisible = false
    }, */
    //新增错题页面的取消按钮
    addCancel() {
      if (this.addFlag) {
        this.addFlag = !this.addFlag
      }
      this.$refs.upload.clearFiles()
      this.clearAddMistake()
      this.addDialogVisible = false
    },
    //新增错题页面的确定按钮
    addConfirm() {
      if (!this.addMistakeData.questionImage) {
        this.$message({
          type: 'error',
          message: '请上传错题图片！'
        })
        return
      }
      this.$refs.addUpload.submit()
      console.log("确定按钮");
      this.addDialogVisible = false
    },
    //新增页面图片上传成功执行的函数
    async addSuccess(res) {
      console.log("addSuccess", this.addMistakeData);
      this.addFlag = true
      this.addMistakeData.questionImage = res.data
      console.log(this.addMistakeData);

      let result = await reqModifyMistake(this.addMistakeData)
      if (result.code == 1) {
        this.$message({
          type: 'success',
          message: '新增错题成功！'
        })
        this.$refs.upload.clearFiles()
        this.clearAddMistake()
        this.getMistakes()
      } else {
        this.$message({
          type: 'error',
          message: '新增错题失败！'
        })
      }
    },
    //新增页面图片发生变化执行的函数
    addChange(file) {
      const reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = () => {
        this.addMistakeData.questionImage = reader.result;
      };
    },
    //清空新增错题数组数据
    clearAddMistake() {
      this.addMistakeData = {
        questionContent: '',
        questionSummary: '',
        questionTitle: '',
        questionAnswer: '',
        subject: '',
        questionImage: '',
        questionAnalysis: ''
      }
    },
    //修改按钮
    modify(row) {
      this.selectedMistake = {...row}
      this.modifyDialogVisible = true
      this.imageUrl = row.questionImage
      if (this.fileCount) {
        this.$refs.upload.clearFiles()
        this.fileCount = 0
      }
    },
    //详情按钮
    details(row) {
      this.selectedMistake = {...row}
      this.detailDialogVisible = true
    },
    //删除按钮
    async deleteMistake(id) {
      let result = await reqDeleteMistake(id)
      console.log(id);
      // eslint-disable-next-line
      if (result.code == 1) {
        this.$message({
          type: 'success',
          message: '删除成功！'
        })
        this.getMistakes();
      } else {
        this.$message({
          type: 'error',
          message: '删除失败！'
        })
      }
    },
    //修改页面清除上传的图片
    deleteFiles() {
      this.photo = false
      this.$refs.upload.clearFiles()
    },
    //修改页面图片发生变化执行的函数
    handleAvatarChange(file) {
      this.fileCount++
      this.count++;
      const reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = () => {
        this.imageUrl = reader.result;
      };
      if (this.count == 1) {
        this.photo = true
      } else {
        this.count = 0
      }
    },
    //修改页面确认按钮
    async confirm() {
      if (this.photo) {
        this.photo = false
        this.$refs.upload.submit()
      } else {
        let result = await reqModifyMistake(this.selectedMistake)
        if (result.code == 1) {
          this.getMistakes();
          this.$message({
            type: 'success',
            message: '错题数据修改成功！'
          })

        } else {
          this.$message({
            type: 'error',
            message: '错题数据修改失败！'
          })
        }
      }
      this.modifyDialogVisible = false
    },
    //修改页面图片上传成功执行的函数
    async handleAvatarSuccess(res) {
      this.selectedMistake.questionImage = res.data
      let result = await reqModifyMistake(this.selectedMistake)
      if (res.code != 1) {
        this.$message({
          type: 'error',
          message: '图片上传失败！'
        })
      } else {
        if (result.code == 1) {
          this.getMistakes();
          this.$message({
            type: 'success',
            message: '图片上传成功！错题数据修改成功！'
          })
        } else {
          this.$message({
            type: 'error',
            message: '错题数据修改失败！'
          })
        }
      }
    },

    /* 炎哥写的 */
    handleCloseTag(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
  },
  mounted() {
    // 加载页面数据
    this.getMistakes();
    this.getAllTag()
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 3px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.image-container {
  position: relative;
}

.el-image {
  display: block;
  width: 178px;
  height: 178px;
}

.avatar-uploader-icon {
  position: absolute;
  top: 0;
  left: 0;
  font-size: 28px;
  color: #409EFF;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;

}

.avatar-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
